<template>
  <el-drawer :visible.sync="drawer" direction="rtl" size="50%" :with-header="false" :width="700">
    <div class="drawer_box">
      <div class="drawer_title">
        <div class="drawer_t">
          <div class="drawer_t_l">
            <img class="drawer_t_l_img" src="/static/skin/herodoo/main/platform/home/img/piliangoumai.png" alt="" />
            开票
          </div>
          <img class="drawer_t_r" src="/static/skin/herodoo/main/platform/home/img/guanbi.png" alt=""
            @click="drawer = false" />
        </div>
      </div>
      <div class="drawer_content">
        <div class="content-box">
          <div class="label">发票：</div>
          <div class="desc">
            <el-upload action="#" multiple :limit="10" accept=".pdf,.ofd,.xml,.jpg,.png" :show-file-list="false"
              :file-list="defaultFile" :http-request="httpRequest" :before-upload="beforeUpload"
              :on-exceed="handleExceed">
              <div class="upload-wrapper">
                <div slot="tip" class="el-upload__tip">
                  文件不超过20MB，支持.pdf、.ofd、.xml.jpg.png格式
                </div>
                <el-button class="" size="small" type="primary">点击上传</el-button>
              </div>
            </el-upload>
            <!-- 文件列表 -->
            <div class="file-container">
              <div class="file-item" v-for="(item, index) in FileList" :key="index">
                <div class="file-action" @click="delFile(index)">删除</div>
                <div class="file-action" @click="filePreview(item, index)">
                  {{
                    item.name.split(".")[1] == "ofd" ||
                      item.name.split(".")[1] == "xml"
                      ? "下载"
                      : "预览"
                  }}
                </div>
                <div class="file-name" @click="filePreview(item, index)">
                  {{ item.name }}
                </div>
                <div>{{ (item.size / 1024 / 1024 || 0).toFixed(2) }}MB</div>
              </div>
            </div>
          </div>
        </div>
        <div class="title">发票信息：</div>
        <div class="content-box">
          <div class="label">抬头：</div>
          <div class="desc">{{ messageList.CompanyName }}</div>
        </div>
        <block v-if="messageList.TypeID == 1">
          <div class="content-box">
            <div class="label">税号：</div>
            <div class="desc">{{ messageList.TaxCode }}</div>
          </div>
          <div class="content-box">
            <div class="label">单位地址：</div>
            <div class="desc">{{ messageList.CompanyAddress }}</div>
          </div>
          <div class="content-box">
            <div class="label">单位电话：</div>
            <div class="desc">{{ messageList.Phone }}</div>
          </div>
          <div class="content-box">
            <div class="label">开户银行：</div>
            <div class="desc">{{ messageList.BankName }}</div>
          </div>
          <div class="content-box">
            <div class="label">银行账号：</div>
            <div class="desc">{{ messageList.BankAccount }}</div>
          </div>
        </block>
        <div class="title">订单信息</div>
        <div class="content-box">
          <div class="label">订单编号：</div>
          <div class="desc">{{ messageList.PayCode }}</div>
        </div>
        <div class="content-box">
          <div class="label">权益名称：</div>
          <div class="desc name" @click="handleShowDetail">
            {{ messageList.Name }}
          </div>
        </div>
        <div class="content-box">
          <div class="label">买家：</div>
          <div class="desc">{{ messageList.PurchaserIDName }}</div>
        </div>
        <!-- <div class="content-box">
          <div class="label">已核销数量：</div>
          <div class="desc">{{ messageList.Quantity }}</div>
        </div> -->
        <div class="content-box">
          <div class="label">服务方：</div>
          <div class="desc">{{ messageList.ServiceCompanyName }}</div>
        </div>

        <div class="title">开票信息</div>
        <div class="content-box">
          <div class="label">申请开票总金额(元)：</div>
          <div class="desc">{{ messageList.Amount }}</div>
        </div>
        <div class="content-box">
          <div class="label">申请开票时间：</div>
          <div class="desc">{{ messageList.CreateTime }}</div>
        </div>

        <!-- <div class="title">已使用列表</div>
        <el-table :data="userCountList" stripe style="width: 100%">
          <el-table-column prop="Name" label="核销码"> </el-table-column>
          <el-table-column prop="Mobile" label="金额(元)"> </el-table-column>
          <el-table-column prop="TypeID" label="应开发票金额(元)">
          </el-table-column>
          <el-table-column prop="PurchaseID" label="使用时间">
          </el-table-column>
        </el-table>
        <div class="end" v-if="total > 0">
          <el-pagination background layout="prev, pager, next" :total="total" :current-page="currentPage"
            :page-size="pageSize" @current-change="handleCurrentChange">
          </el-pagination>
        </div> -->
      </div>
      <div class="drawer_footer">
        <button class="footer-btn" @click="handleUpdate">保存</button>
      </div>
    </div>
    <!-- 查看权益弹窗 -->
    <rights-detail :octopus="octopus" ref="rightsDetail"></rights-detail>

    <!-- 预览文件 -->
    <el-drawer :visible.sync="fileDrawer" direction="rtl" size="50%" :with-header="false" :width="700" append-to-body>
      <embed v-if="fileSrc" :type="fileType" :src="fileSrc" style="width: 100%; height: 100%;" />
      <!-- <image v-if="imgurl" :src="imgurl"></image> -->
      <div class="imgs">
        <el-image v-if="imgurl" :src="imgurl" fit="contain"></el-image>
      </div>

    </el-drawer>

    <iframe :src="documentUrl" style="opacity: 0;"></iframe>
  </el-drawer>
</template>

<script>
import rightsDetail from "./rightsDetail.vue";
export default {
  components: { rightsDetail },
  props: {
    messageList: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      octopus: this.$parent.octopus,
      drawer: false,
      fileDrawer: false,
      documentUrl: "",
      catList: [],
      tabID: 2,
      FileList: [],
      userCountList: [],
      total: 0,
      currentPage: 1, //当前页
      pageSize: 10, // 每页显示条数
      imgurl: null
    };
  },
  computed: {
    defaultFile() {
      return this.messageList.FilePath
        ? JSON.parse(this.messageList.FilePath)
        : [];
    }
  },
  watch: {
    drawer(v) {
      if (v) {
        if (this.messageList.FilePath) {
          try {
            this.FileList = JSON.parse(this.messageList.FilePath) || [];
          } catch (e) { }
        } else this.FileList = [];
        this.getCancelList();
      }
    },
    deep: true
  },
  methods: {
    drawerOp() {
      this.drawer = true;
    },
    // 保存
    handleUpdate() {
      if (!this.FileList.length) {
        this.$message.error("请选择发票文件");
        return;
      }
      this.$confirm("是否确认开具发票", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.octopus.request.api.post(
          "/Octopus/Engine/Item",
          {
            id: 1211,
            type: "UPDATE",
            value: this.messageList.InvoiceID,
            cellData: [
              { name: "FilePath", defaultValue: JSON.stringify(this.FileList) },
              // {name: "ReopenTime", defaultValue: new Date().toJSON().substring(0, 10) + ' ' + new Date().toTimeString().substring(0,8)},	// 开票时间
              { name: "IsDelete", defaultValue: 0 }, // 是否重开 （0 正常，1 重开）
              {
                name: "BillingTime",
                defaultValue:
                  new Date().toJSON().substring(0, 10) +
                  " " +
                  new Date().toTimeString().substring(0, 8)
              } // BillingTime
            ]
          },
          data => {
            if (data.status.code == 200) {
              this.$message.success("申请开具发票成功");
              if (this.messageList.TypeID == 1) {
                // 获取用户组
                this.$utils.getGroupInfo(this, '超级管理员,平台财务,企业高级管理员,企业财务', this.messageList.PurchaserID).then((res) => {
                  console.log('发送消息的用户组：', res);
                  // 发送消息 传值说明 模版ID ，消息类型 ，消息里的字段 ，创建用户ID，接收公司ID，接收群组ID
                  res.length > 0 && this.$utils.sendMessageMulti(12, 3, { PayCode: this.messageList.PayCode }, this.octopus.passport.id, this.messageList.PurchaserID, res, this)
                });
              } else {
                // 发送消息 to C, 传值说明 模版ID ，消息类型 ，消息里的字段 ，创建用户ID，接收人ID
                this.$utils.sendMessageAlone(30, 3, { PayCode: this.messageList.PayCode, EquityName: this.messageList.Name, Number: this.messageList.Quantity }, this.octopus.passport.id, this.messageList.PurchaserID, this);
              }


              this.drawer = false;
              this.$emit("refresh");
            } else {
              this.octopus.tips.error(data);
            }
          }
        );
      });
    },
    httpRequest({ file }) {
      if (file.size == 0) {
        this.$message.error("请检查文件是否正确！");
        return;
      }
      this.octopus.request.api.upload(
        file,
        data => { },
        res => {
          if (res.status.code == 200) {
            this.FileList.push({
              url: this.octopus.config.url + res.content.url,
              name: res.content.name,
              size: res.content.size
            });
          } else {
            this.$message.error("上传失败,请重新上传！");
          }
        }
      );
    },
    beforeUpload(file) {

      const isExcel = /\.(pdf|ofd|xml|jpg|png)$/.test(file.name);

      if (!isExcel) {
        this.$message.error("只能上传pdf,ofd,xml,jpg,png文件！");
        return false;
      }
      if (this.FileList.length >= 10) {
        this.$message.error("最多上传10个文件！");
        return false;
      }
      let size = file.size;
      if (size / 1024 / 1024 > 20) {
        this.$message.error("上传文件过大,不能超过20MB,请重新选择！");
        return false
      }
      return true;
    },
    handleExceed() {
      this.$message.error("最多上传10个文件！");
    },
    // 删除文件
    delFile(index) {
      this.$confirm("是否删除这个文件?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(res => {
          this.FileList.splice(index, 1);
        })
        .catch(e => { });
    },
    downLoad(str, name) {
      let url = str;
      fetch(url)
        .then(response => response.blob())
        .then(blob => {
          const a = document.createElement("a");
          a.href = window.URL.createObjectURL(blob);
          a.download = name;
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(a.href);
          document.body.removeChild(a);
        });
    },
    // 预览文件
    filePreview(item, index) {
      let name = item.name.split(".");
      
      this.imgurl = null;
      this.fileSrc = null;
      if (name[1] == 'jpg' || name[1] == 'png') {
        this.imgurl = item.url;
        this.fileDrawer = true;
        return
      }

      if (name[1] == "xml" || name[1] == "ofd") {
        setTimeout(() => {
          this.downLoad(item.url, item.name);
        }, 500);
        return;
      }

      let file_path = item.url.substring(item.url.indexOf("upload") + 6);
      let view_path =
        this.octopus.config.url +
        "/Octopus/Engine/Viewer/" +
        item.name +
        "?" +
        "path=" +
        file_path +
        "&access_token=" +
        this.octopus.passport.token;

      let arr = item.name.split(".");
      let type = arr[arr.length - 1];
      this.fileType = `application/${type}`;
      this.fileSrc = view_path;
      this.fileDrawer = true;
    },
    // 核销列表
    getCancelList() {
      this.octopus.request.api.post(
        "/Octopus/Engine/List",
        {
          id: 1264,
          cellData: [
            { name: "ID" }, // ID
            { name: "UserPayTotalPrice" }, // 核销金额(元)
            { name: "VerificeCode" }, // 核销码
            { name: "VerificeTime" } // 核销时间
          ],
          paramData: {
            Code: this.messageList.PayCode,
            PurchaseID: this.messageList.PurchaseID
          },
          pageData: {
            index: this.currentPage,
            rowSize: this.pageSize
          }
        },
        data => {
          if (data.status.code == 200) {
            this.total = data.content.pageData.totalRows;
            this.concelList = data.content.queryData;
          } else {
            this.octopus.tips.error(data);
          }
        }
      );
    },
    // 展示权益详情
    handleShowDetail() {
      this.$refs.rightsDetail.init(this.messageList.EquityID);
      this.$refs.rightsDetail.drawerOp();
    }
  }
};
</script>
<style scoped>
.drawer_box {
  padding: 3rem 0.8rem 3rem 0;
  height: calc(100% - 5rem);
  display: flex;
  flex-direction: column;
}

.drawer_title {
  box-shadow: 0px 5px 5px rgb(230 228 228 / 30%);
  padding-bottom: 1rem;
}

.drawer_t {
  padding: 0 2.8rem;
  display: flex;
  justify-content: space-between;
}

.drawer_t_l {
  display: flex;
  align-items: center;
  font-size: 2rem;
  font-weight: bold;
}

.drawer_t_l_img {
  width: 2.8rem;
  margin-right: 1rem;
}

.drawer_t_r {
  width: 3rem;
  height: 3rem;
  cursor: pointer;
}

.button_box {
  margin-top: 1rem;
  padding: 0 3rem;
  display: flex;
}

.drawer_content {
  overflow-y: auto;
  margin-top: 1.5rem;
  height: calc(100vh - 14rem);
  padding: 0 3rem;
  width: 100%;
  padding-bottom: 1rem;
}

.drawer_content .title {
  font-size: 1.8rem;
  font-weight: bold;
}

.drawer_content .driver-title {
  margin-top: 1em;
}

.content-box {
  display: flex;
  align-items: center;
  margin: 2rem 0 2rem 2em;
}

.mt-10 {
  margin-top: 10rem;
}

.content-box .label {
  width: 25%;
}

.content-box .label .label-bold {
  font-size: 1.8rem;
  font-weight: bold;
}

.content-box .desc {
  flex: 1;
}

.upload-wrapper {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.file-container .file-item {
  height: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid rgba(0, 0, 0, 0.3);
}

.file-container .file-item .file-action {
  cursor: pointer;
  width: 5%;
}

.file-container .file-item .file-name {
  width: 70%;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #288ffd;
  text-decoration: underline;
  cursor: pointer;
}

.name {
  color: #288ffd;
  text-decoration: underline;
  cursor: pointer;
}

.drawer_footer {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-right: 30px;
}

.drawer_footer .footer-btn {
  line-height: 4rem;
  background-color: #f78c51;
  color: #fff;
  margin: 0 1rem;
  padding: 0 3rem;
  border-radius: 0.5rem;
  cursor: pointer;
  border: none;
  font-size: 1.6rem;
}

>>>.el-upload--picture-card {
  width: 100%;
  background-color: transparent;
  border: 0;
  height: inherit;
  line-height: inherit;
}

.end {
  display: flex;
  justify-content: flex-end;
}

>>>.el-pagination.is-background .el-pager li:not(.disabled).active {
  background-color: #ff8a36;
}
.imgs >>>.el-image{
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.imgs >>> img {
  width: 50%;
}
</style>
